<script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import ImageUploader from '@/components/admin/ImageUploader.vue'
import CategoryTagSelector from '@/components/admin/CategoryTagSelector.vue'
import errorLogger from '@/utils/errorLogger'
import { publishArticleAPI, getArticleByIdAPI, updateArticleAPI } from '@/api'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

const form = ref({
  title: '',
  summary: '',
  content: '',
  coverImage: '',
  category: '',
  tags: [],
})

// 路由与编辑状态判断
const route = useRoute()
const router = useRouter()
const routeId = route.params.id
const isEditing = !!routeId

// 加载文章数据（编辑时调用）
const loadArticle = async (id) => {
  try {
    const res = await getArticleByIdAPI(id)
    // 假设接口返回 { data: { title, summary, content, coverImage, category, tags } }
    const d = res.data || {}
    form.value.title = d.title || ''
    form.value.summary = d.summary || ''
    form.value.content = d.content || ''
    form.value.coverImage = d.coverImage || ''
    // API 可能返回的是对象（已 populate）或只是 id 字符串。
    // 如果是对象，取其 _id（或 id），否则直接使用字符串 id；确保传入 CategoryTagSelector 的是字符串 id
    const categoryId =
      d.category && typeof d.category === 'object'
        ? d.category._id || d.category.id
        : d.category || ''
    form.value.category = categoryId

    // tags 可能是 ['id', ...] 或 [{_id, name}, ...]，统一映射为 id 数组
    form.value.tags = Array.isArray(d.tags)
      ? d.tags.map((t) => (typeof t === 'object' ? t._id || t.id : t))
      : []
  } catch (err) {
    errorLogger(err)
  }
}

// 提交文章：创建或更新都走这里
const publishArticle = async () => {
  try {
    if (isEditing) {
      // 更新文章，确保把 id 附带上
      await updateArticleAPI({ id: routeId, ...form.value })
      ElMessage.success('文章更新成功')
      // 更新完成后跳回文章列表
      router.push('/admin-layout/article')
    } else {
      await publishArticleAPI(form.value)
      ElMessage.success('文章发布成功')
      router.push('/admin-layout/article')
    }
  } catch (error) {
    errorLogger(error)
  }
}

// 富文本编辑器
const editorRef = shallowRef()
const handleCreated = (editor) => (editorRef.value = editor)
onBeforeUnmount(() => editorRef.value?.destroy())

// 如果是编辑页面，在挂载时加载文章
onMounted(() => {
  if (isEditing) loadArticle(routeId)
})
</script>

<template>
  <div class="editor-container">
    <!-- 文章标题 -->
    <el-form :model="form" label-width="100px" class="article-title">
      <el-form-item label="文章标题" prop="title">
        <el-input
          v-model="form.title"
          placeholder="请输入文章标题"
          size="large" />
      </el-form-item>
    </el-form>

    <!-- 文章内容 -->
    <div class="editor-wrapper">
      <Toolbar :editor="editorRef" mode="default" class="toolbar" />
      <Editor
        v-model="form.content"
        mode="default"
        @onCreated="handleCreated"
        class="editor" />
    </div>

    <!-- 其它信息 -->
    <el-form :model="form" label-width="100px" class="article-info">
      <!-- 摘要 -->
      <el-form-item label="文章摘要" prop="summary">
        <el-input
          v-model="form.summary"
          type="textarea"
          :rows="3"
          placeholder="请输入文章摘要" />
      </el-form-item>

      <!-- 分类和标签 -->
      <CategoryTagSelector
        v-model:category="form.category"
        v-model:tags="form.tags" />

      <!-- 封面 -->
      <el-form-item label="封面图片" prop="coverImage">
        <ImageUploader v-model="form.coverImage" />
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button @click="publishArticle" type="primary" size="large">
          {{ isEditing ? '更新文章' : '发布文章' }}
        </el-button>
        <el-button size="large">保存草稿</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style lang="scss" scoped>
.editor-container {
  padding: 20px;
  background-color: $color-white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  .article-title {
    margin-bottom: 20px;
    .el-form-item {
      display: flex;
      align-items: center;

      :deep(.el-form-item__label) {
        font-size: 18px;
        font-weight: bold;
      }
    }
  }

  .editor-wrapper {
    .toolbar {
      border: 2px solid $color-border;
      border-radius: 8px 8px 0 0;
      overflow: hidden;
    }

    .editor {
      height: 600px !important;
      border: 2px solid $color-border;
      border-top: none;
      border-radius: 0 0 8px 8px;
      overflow: hidden;
    }
  }

  .article-info {
    margin-top: 28px;
  }
}

:deep(.w-e-full-screen-container) {
  z-index: 99999 !important;
}
</style>
